package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.pojo.Admin;
import com.itheima.service.AdminService;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/creatCode")
public class CreateCodeController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminService adminService;

    //注册发送验证码
    private static final String REGISTER_CODE_ = "register_code_";

    @PostMapping("/validCode")
    public Result sendvalidCode(@RequestBody Map info) {
        Object message = info.get("info");
        if (message == null || "".equals(message)) {
            return new Result("fail", "请输入手机号或邮箱");
        }
        //生成验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        String str = message.toString();
        //注册的为
        if (!str.contains("@")) {
            Admin admin = adminService.findByphone(str);
            //号码已被注册
            if (admin != null) {
                return new Result("fail", "号码已被使用");
            }
            System.out.println("验证码：" + validateCode);
            try {
                //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, mobile, validateCode.toString());
                //将短信保存在redis中5分钟
                redisTemplate.opsForValue().set(REGISTER_CODE_ + str, validateCode.toString());
                redisTemplate.expire(REGISTER_CODE_ + str, 5, TimeUnit.MINUTES);//保存5分钟
            } catch (Exception e) {
                e.printStackTrace();
                return new Result("fail", "验证码发送失败");
            }
            return new Result("success", "发送消息成功");
        }/*else {//邮箱发送
            Admin admin = adminService.findByEmail(str);
            if (admin!=null){
                return new Result("fail","邮箱已被使用");
            }
            SimpleMailMessage message = new SimpleMailMessage();
            message.setText("您的博客注册验证码为"+validateCode);
            message.setSubject("验证码");
            //发送者邮箱
            message.setFrom("1131640056@qq.com");
            //发送到哪个邮箱
            message.setTo(str);
            javaMailSender.send(message);
        }*/
        return new Result("success", "验证码发送成功");
    }
}
